﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Swift;
using SCM;

namespace Server
{
    /// <summary>
    /// 抽卡升级等各种卡片相关
    /// </summary>
    public class CardManager : Component
    {
        UserPort UP;

        public override void Init()
        {
            UP = GetCom<UserPort>();

            UP.OnRequest("DrawCard", OnDrawCard);
            UP.OnRequest("CombineOrUpgradeUnit", OnCombineOrUpgradeUnit);
        }

        #region 响应处理用户消息

        #endregion

        // 新用户初始化卡包
        public void InitUserCards(User usr)
        {
            usr.AddUnit("CommanderCenter", 1);
            usr.AddUnit("CCAcc", 1);
            usr.AddUnit("Barrack", 1);
            usr.AddUnit("Soldier", 1);
            usr.AddUnit("Firebat", 1);
        }

        string[] noneNeutralUnits = null;
        void PrepareNoneNeutralUnits()
        {
            if (noneNeutralUnits == null)
            {
                var lst = new List<string>();
                foreach (var c in UnitConfiguration.AllConfigNames)
                {
                    var cfg = UnitConfiguration.GetDefaultConfig(c);
                    if (cfg.NeutralType)
                        continue;

                    lst.Add(c);
                }

                noneNeutralUnits = lst.ToArray();
            }
        }

        // 随机抽卡
        const int DrawCardCost = 1;
        public void OnDrawCard(Session s, IReadableBuffer data, IWriteableBuffer buff)
        {
            var info = s.Usr.Info;
            if (info.Coins < DrawCardCost)
            {
                buff.Write(false);
                return;
            }

            info.Coins -= DrawCardCost;
            PrepareNoneNeutralUnits();
            var c = noneNeutralUnits.SwiftRandomSort()[0];
            info.AddCard(c, 1);
            buff.Write(true);
            buff.Write(c);
        }

        // 合成或升级单位
        public void OnCombineOrUpgradeUnit(Session s, IReadableBuffer data, IWriteableBuffer buff)
        {
            var info = s.Usr.Info;
            var c = data.ReadString();
            buff.Write(info.CombineOrUpgradeUnit(c));
        }
    }
}
